package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : Sonic
 * @version : 1.0
 * @createTime : 2024-12-08  14:42
 * @description :
 */

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    // 除了调用mapper，也可以调用service
    @Autowired
    private WorkspaceService workspaceService;


    /**
     * @param: [begin, end]
     * @return: com.sky.vo.TurnoverReportVO
     * @description: 统计指定时间内的营业额数据
     **/
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 构造从begin到End的每一天
        List<LocalDate> dateList = getDateList(begin, end);
        // 拼接字符串
        String join = StringUtils.join(dateList, ",");

        // 查询营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            // 若当天订单为空，则手动将营业额设置为0.0
            turnoverList.add(turnover == null ? 0.0 : turnover);
        }
        // 拼接字符串
        String joinTurnover = StringUtils.join(turnoverList, ",");

        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(join)
                .turnoverList(joinTurnover)
                .build();
        return turnoverReportVO;
    }

    /**
     * @param: [begin, end]
     * @return: com.sky.vo.UserReportVO
     * @description: 用户量和新增用户量统计
     **/
    @Override
    public UserReportVO getUerStatistics(LocalDate begin, LocalDate end) {
        // 构造从begin到End的每一天
        List<LocalDate> dateList = getDateList(begin, end);
        // 拼接字符串
        String joinDate = StringUtils.join(dateList, ",");
        // 统计数据List
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", endTime);
            // 总用户数量
            Integer countTotal = userMapper.countByMap(map);
            totalUserList.add(countTotal);
            map.put("begin", beginTime);
            // 当日新增用户数量
            Integer countNew = userMapper.countByMap(map);
            newUserList.add(countNew);
        }
        // 拼接字符串
        String joinTotalUserList = StringUtils.join(totalUserList, ",");
        String joinNewUserList = StringUtils.join(newUserList, ",");
        // 构造VO对象
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(joinDate)
                .totalUserList(joinTotalUserList)
                .newUserList(joinNewUserList)
                .build();
        return userReportVO;
    }

    /**
     * @param: [begin, end]
     * @return: com.sky.vo.OrderReportVO
     * @description: 订单数据统计
     **/
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        // 构造从begin到End的每一天
        List<LocalDate> dateList = getDateList(begin, end);
        // 拼接字符串
        String joinDate = StringUtils.join(dateList, ",");

        // 统计数据List
        List<Integer> totalOrderList = new ArrayList<>();
        List<Integer> validOrderList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            // 每日总订单数量
            Integer countTotal = orderMapper.countOrderByMap(map);
            totalOrderList.add(countTotal);
            // 每日有效订单数量
            map.put("status", Orders.COMPLETED);
            Integer countValid = orderMapper.countOrderByMap(map);
            validOrderList.add(countValid);

            // 累计总量
            totalOrderCount += countTotal;
            validOrderCount += countValid;
        }

        // 拼接字符串
        String joinTotalOrderList = StringUtils.join(totalOrderList, ",");
        String joinValidOrderList = StringUtils.join(validOrderList, ",");

        // 构造VO对象
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(joinDate)
                .orderCountList(joinTotalOrderList)
                .validOrderCountList(joinValidOrderList)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(totalOrderCount == 0 ? 0.0 : validOrderCount.doubleValue() / totalOrderCount)
                .build();
        return orderReportVO;
    }

    /**
     * @param: [begin, end]
     * @return: com.sky.vo.SalesTop10ReportVO
     * @description: 订单商品销量前十统计（dish和 setmeal）
     **/
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesDTOList = orderMapper.getSalesTop(beginTime, endTime);
        // 统计数据List
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        // TODO Stream流的写法
        for (GoodsSalesDTO goodsSalesDTO : salesDTOList) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }
        String joinNameList = StringUtils.join(nameList, ",");
        String joinNumberList = StringUtils.join(numberList, ",");

        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(joinNameList)
                .numberList(joinNumberList)
                .build();
        return salesTop10ReportVO;
    }

    /**
     * @param: [begin, end]
     * @return: java.util.List<java.time.LocalDate>
     * @description: 构造从begin到End的每一天, 返回 List
     **/
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        // 构造从begin到End的每一天
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * @param: [httpServletResponse]
     * @return: void
     * @description: 导出运营数据报表
     **/
    @Override
    public void exportBusinessData(HttpServletResponse httpServletResponse) {
        // 查询数据库
        // 概览数据查询
        LocalDate now = LocalDate.now();
        LocalDate begin = now.minusDays(30);
        LocalDate end = now.minusDays(1);
        // 起止日期
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);
        // 读取模板文件, 创建新文件
        try {
            InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);
            XSSFSheet sheet1 = excel.getSheet("Sheet1");

            // 概览数据：以30天为单位查询数据
            // 时间
            sheet1.getRow(1).getCell(1).setCellValue("起止时间：" + begin + " 至 " + end);
            // 营业额
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            // 完单率
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            // 新用户
            row.getCell(6).setCellValue(businessData.getNewUsers());
            // 有效订单
            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            // 平均客单价
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            // 明细数据：以天为单位查询数据
            //
            for (int i = 0; i < 30; i++) {
                LocalDate localDate = begin.plusDays(i);
                LocalDateTime localDateBegin = LocalDateTime.of(localDate, LocalTime.MIN);
                LocalDateTime localDateEnd = LocalDateTime.of(localDate, LocalTime.MAX);
                BusinessDataVO dataVO = workspaceService.getBusinessData(localDateBegin, localDateEnd);
                row = sheet1.getRow(7+i);

                row.getCell(1).setCellValue(localDate.toString());
                row.getCell(2).setCellValue(dataVO.getTurnover());
                row.getCell(3).setCellValue(dataVO.getValidOrderCount());
                row.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(dataVO.getUnitPrice());
                row.getCell(6).setCellValue(dataVO.getNewUsers());
            }

            // 通过输出流下载文件
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            excel.write(outputStream);
            // 关闭资源
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
